<?php
session_start();
include('../includes/config.php');
include('../includes/functions.php');

// 检查用户是否已登录，且是医生角色
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] != 'doctor') {
    header("Location: ../login.php");
    exit();
}

// 获取医生信息
$doctor_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT * FROM users u JOIN doctors d ON u.id = d.user_id WHERE u.id = ?");
$stmt->bind_param("i", $doctor_id);
$stmt->execute();
$doctor_info = $stmt->get_result()->fetch_assoc();
$stmt->close();

// 处理筛选参数
$patient_filter = isset($_GET['patient']) ? $_GET['patient'] : '';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$diagnosis_filter = isset($_GET['diagnosis']) ? $_GET['diagnosis'] : '';

// 构建查询
$sql = "SELECT mr.*, p.name as patient_name, p.id_card, p.gender, p.birthday, p.phone 
        FROM medical_records mr 
        JOIN patients p ON mr.patient_id = p.id 
        WHERE mr.doctor_id = ?";
$params = array($doctor_info['id']);
$types = "i";

// 添加筛选条件
if (!empty($patient_filter)) {
    $sql .= " AND (p.name LIKE ? OR p.id_card LIKE ?)";
    $search_term = "%$patient_filter%";
    $params[] = $search_term;
    $params[] = $search_term;
    $types .= "ss";
}

if (!empty($date_from)) {
    $sql .= " AND DATE(mr.created_at) >= ?";
    $params[] = $date_from;
    $types .= "s";
}

if (!empty($date_to)) {
    $sql .= " AND DATE(mr.created_at) <= ?";
    $params[] = $date_to;
    $types .= "s";
}

if (!empty($diagnosis_filter)) {
    $sql .= " AND mr.diagnosis LIKE ?";
    $params[] = "%$diagnosis_filter%";
    $types .= "s";
}

// 添加排序
$sql .= " ORDER BY mr.created_at DESC";

// 准备和执行查询
$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$records = $stmt->get_result();
$stmt->close();
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>病历管理 - 医生工作站</title>
    <link rel="stylesheet" href="/assets\css/bootstrap_69c9e605.min.css">
    <link rel="stylesheet" href="/assets\css/style.css">
    <link rel="stylesheet" href="/assets\css/all_de197510.min.css">
    <link rel="stylesheet" href="/assets\css/flatpickr_01e5beab.min.css">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <nav id="sidebar" class="col-md-3 col-lg-2 d-md-block bg-dark sidebar collapse">
                <div class="position-sticky pt-3">
                    <div class="text-center mb-4">
                        <img src="../assets/images/hospital-logo.png" alt="医院标志" class="img-fluid rounded-circle mx-auto d-block" style="width: 80px;">
                        <h5 class="text-white mt-2"><?php echo htmlspecialchars($doctor_info['name']); ?></h5>
                        <p class="text-muted"><?php echo htmlspecialchars($doctor_info['department_name']); ?></p>
                    </div>
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link text-white" href="index.php">
                                <i class="fas fa-home"></i> 工作台首页
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="appointments.php">
                                <i class="fas fa-calendar-check"></i> 预约管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="patients.php">
                                <i class="fas fa-user-injured"></i> 患者管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active text-white" href="records.php">
                                <i class="fas fa-notes-medical"></i> 病历管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="prescriptions.php">
                                <i class="fas fa-prescription"></i> 处方管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="schedule.php">
                                <i class="fas fa-clock"></i> 排班管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="profile.php">
                                <i class="fas fa-user-md"></i> 个人信息
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="../logout.php">
                                <i class="fas fa-sign-out-alt"></i> 退出登录
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- 主内容区 -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">病历管理</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <a href="create_record.php" class="btn btn-sm btn-outline-primary">
                            <i class="fas fa-plus"></i> 新建病历
                        </a>
                    </div>
                </div>

                <!-- 筛选表单 -->
                <div class="card mb-4">
                    <div class="card-body">
                        <form action="" method="GET" class="row g-3">
                            <div class="col-md-3">
                                <label for="patient" class="form-label">患者信息</label>
                                <input type="text" class="form-control" id="patient" name="patient" placeholder="姓名或身份证号" value="<?php echo htmlspecialchars($patient_filter); ?>">
                            </div>
                            <div class="col-md-2">
                                <label for="date_from" class="form-label">开始日期</label>
                                <input type="date" class="form-control datepicker" id="date_from" name="date_from" value="<?php echo $date_from; ?>">
                            </div>
                            <div class="col-md-2">
                                <label for="date_to" class="form-label">结束日期</label>
                                <input type="date" class="form-control datepicker" id="date_to" name="date_to" value="<?php echo $date_to; ?>">
                            </div>
                            <div class="col-md-3">
                                <label for="diagnosis" class="form-label">诊断</label>
                                <input type="text" class="form-control" id="diagnosis" name="diagnosis" placeholder="诊断关键词" value="<?php echo htmlspecialchars($diagnosis_filter); ?>">
                            </div>
                            <div class="col-md-2 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary w-100">筛选</button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- 病历列表 -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">病历列表</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead class="table-light">
                                    <tr>
                                        <th>ID</th>
                                        <th>患者姓名</th>
                                        <th>性别</th>
                                        <th>年龄</th>
                                        <th>诊断</th>
                                        <th>创建时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if ($records->num_rows > 0): ?>
                                        <?php while ($record = $records->fetch_assoc()): 
                                            // 计算患者年龄
                                            $birthday = new DateTime($record['birthday']);
                                            $today = new DateTime();
                                            $age = $birthday->diff($today)->y;
                                        ?>
                                            <tr>
                                                <td><?php echo $record['id']; ?></td>
                                                <td><?php echo htmlspecialchars($record['patient_name']); ?></td>
                                                <td><?php echo htmlspecialchars($record['gender']); ?></td>
                                                <td><?php echo $age; ?>岁</td>
                                                <td>
                                                    <?php 
                                                    $diagnosis = htmlspecialchars($record['diagnosis']);
                                                    echo strlen($diagnosis) > 30 ? substr($diagnosis, 0, 30) . '...' : $diagnosis; 
                                                    ?>
                                                </td>
                                                <td><?php echo date('Y-m-d H:i', strtotime($record['created_at'])); ?></td>
                                                <td>
                                                    <div class="btn-group">
                                                        <a href="record_details.php?id=<?php echo $record['id']; ?>" class="btn btn-sm btn-info">
                                                            <i class="fas fa-eye"></i>
                                                        </a>
                                                        <a href="edit_record.php?id=<?php echo $record['id']; ?>" class="btn btn-sm btn-primary">
                                                            <i class="fas fa-edit"></i>
                                                        </a>
                                                        <a href="print_record.php?id=<?php echo $record['id']; ?>" class="btn btn-sm btn-secondary" target="_blank">
                                                            <i class="fas fa-print"></i>
                                                        </a>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="7" class="text-center">没有找到符合条件的病历记录</td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- 脚本 -->
    <script src="/assets\js/jquery-3.6.0.min.js"></script></script></script>
    <script src="/assets\js/bootstrap.bundle.min.js"></script></script></script>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <script src="/assets\js/zh_c5ee11e1.js"></script></script></script></script>
    <script>
        // 初始化日期选择器
        document.addEventListener('DOMContentLoaded', function() {
            flatpickr(".datepicker", {
                locale: "zh",
                dateFormat: "Y-m-d",
                allowInput: true
            });
        });
    </script>
</body>
</html> 